package cn.jathlon.datastructure;

import gnu.trove.map.hash.TObjectIntHashMap;

import java.util.List;

/**
 * 独立“词典”类，即"词项(String)"~到“索引(原生int类型)”的映射,“索引”对用户透明。
 * 1：不支持remove
 * 2：不支持iterator
 * 3：Dictionary不是线程安全的。
 * 
 * @author chen
 *
 */
public class Dictionary {

	private int size;
	private TObjectIntHashMap<String> wordMap;
	public Dictionary(){
		size = 0;
		wordMap = new TObjectIntHashMap<String>(1);
	}
	
	/**
	 * 
	 * @param word
	 */
	public void addWord(String word){
		wordMap.putIfAbsent(word, size++);
	}
	
	/**
	 * 返回原生类型索引
	 * 不包含返回-1
	 * @param word
	 */
	public int getIndexIgnoreIfAbsent(String word){
		return wordMap.containsKey(word) ? wordMap.get(word) : -1;
	}
	
	/**
	 * 若不包含，将item增添至词典并返回原生类型索引
	 * @param word
	 */
	public int getIndexAddIfAbsent(String word){
		wordMap.putIfAbsent(word, size++);
		return wordMap.get(word);
	}
	
	/**
	 * 获取Dictionary长度
	 * @return
	 */
	public int size(){
		return this.size;
	}
	
	/**
	 * 批量新增
	 * @param args
	 */
	public void addWords(List<String> wordList){
		for (String word : wordList) {
			wordMap.putIfAbsent(word, size++);
		}
	}
	
	/////////////////////
	public static void main(String[] args) {
		
		Dictionary d = new Dictionary();
		d.addWord("hehe");
		System.out.println(d.getIndexIgnoreIfAbsent("fhasdf"));
		System.out.println(d.size());
		System.out.println(d.getIndexAddIfAbsent("fhasdf"));
		System.out.println(d.size());
	}
	
}
